package com.zhu.ssm.controller;

import com.zhu.ssm.exception.BusinessException;
import com.zhu.ssm.pojo.User;
import com.zhu.ssm.pojo.vo.Result;
import com.zhu.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("findUser/{id}")
    public User findUser(@PathVariable Long id){
        return userService.findUser(1L);
    }

    @GetMapping("test")
    @ResponseBody
    public String test(){
        int age=20;
        if(age<30){
            throw new BusinessException(-999,"系统异常！");
        }
        return "test";
    }

    @PostMapping("save")
    public String save(@RequestBody User user){
        userService.save(user.getAge(),user.getEmail(),user.getName());
        return "success";
    }

    @PostMapping("add")
    public Result add(@RequestBody @Valid User user, Errors errors){
        Result result=new Result();
        if(errors.hasErrors()){
            List<FieldError> fieldErrors = errors.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                result.setCode(500);
                result.setMessage(fieldError.getDefaultMessage());
                result.setSuccess(false);
                result.setData(user);
            }
        }else{
            result.setCode(200);
            result.setMessage("success");
            result.setSuccess(true);
            result.setData(user);
        }
        return result;
    }
}
